package com.example.myapp.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapp.ADO.ActivityManager;
import com.example.myapp.ADO.FullyGridLayoutManager;
import com.example.myapp.ADO.GridImageAdapter;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Article;
import com.example.myapp.Model.Money;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.Permission;
import com.luck.picture.lib.permissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UploadBatchListener;
import cn.bmob.v3.listener.UploadFileListener;
import io.reactivex.functions.Consumer;

public class AddArticle extends AppCompatActivity {

    private ShapeLoadingDialog  shapeLoadingDialog;
    private EditText addArticle_content;
    private int maxSelectNum = 6;
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private RecyclerView mRecyclerView;
    private PopupWindow pop;
    private  ArrayList<String> ImgList=new ArrayList<>();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    saveimgPost();
                    break;
                case 2:
                    savePost();
                    break;
                default:break;

            }
        }

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ActivityManager.getInstance().addActivity(this);
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);  //隐藏标题栏
        setContentView(R.layout.activity_add_article);
         ImageView addArticle_back=findViewById(R.id.addArticle_back);
         Button addArticle_go=findViewById(R.id.addArticle_go);
         addArticle_content=findViewById(R.id.addArticle_content);
        LinearLayout addArticle_gg=findViewById(R.id.addArticle_gg);

        mRecyclerView = findViewById(R.id.recycler);
        //初始化多选图片配置

        initWidget();


        TextWatcher watcher=new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Toast.makeText(getApplicationContext(), "输入之前", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //Toast.makeText(getApplicationContext(), "在输入中", Toast.LENGTH_SHORT).show();
               if( addArticle_content.getText().toString().trim().length()>0){
                   addArticle_go.setBackgroundColor(Color.parseColor("#0F9C57"));
                   addArticle_go.setTextColor(Color.parseColor("#FFFFFF"));//
               }else {
                   addArticle_go.setBackgroundColor(Color.parseColor("#E6EFDE"));
                   addArticle_go.setTextColor(Color.parseColor("#8E8080"));//
               }

            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        addArticle_content.addTextChangedListener(watcher);
        //文本框监听结束
        addArticle_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        addArticle_gg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(AddArticle.this, Notice.class);
                intent.putExtra("title", "莆院帮管理规范");//打开主页
                intent.putExtra("path", "file:///android_asset/notice.html");//打开主页
                startActivity(intent);
            }
        }); //公告

//        发布按钮
        addArticle_go.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(addArticle_content.getText().toString().trim().length()>0){
                    if(selectList.size()>0){
                        //有图片
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }else {
                    //     没图片
                        Message message = new Message();
                        message.what = 2;
                        handler.sendMessage(message);
                    }

                }else {
                    Toast.makeText(AddArticle.this, "发布内容不能为空！", Toast.LENGTH_SHORT).show();

                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;

        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {// 图片选择结果回调
                images = PictureSelector.obtainMultipleResult(data);
                selectList.addAll(images);
                //selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                adapter.setList(selectList);
                adapter.notifyDataSetChanged();

            }
        }
    }


    //图片选择

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @SuppressLint("CheckResult")
        @Override
        public void onAddPicClick() {
            //获取写的权限
            RxPermissions rxPermission = new RxPermissions(AddArticle.this);
            rxPermission.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .subscribe(new Consumer<Permission>() {
                        @Override
                        public void accept(Permission permission) {
                            if (permission.granted) {// 用户已经同意该权限
                                //第一种方式，弹出选择和拍照的dialog
                                showPop();

                                //第二种方式，直接进入相册，但是 是有拍照得按钮的
//                                showAlbum();
                            } else {
                                Toast.makeText(AddArticle.this, "拒绝", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }
    };




    private void showPop() {
        View bottomView = View.inflate(AddArticle.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        //相册
                        PictureSelector.create(AddArticle.this)
                                .openGallery(PictureMimeType.ofImage())
                                .maxSelectNum(maxSelectNum)
                                .minSelectNum(1)
                                .imageSpanCount(4)
                                .selectionMode(PictureConfig.MULTIPLE)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_camera:
                        //拍照
                        PictureSelector.create(AddArticle.this)
                                .openCamera(PictureMimeType.ofImage())
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_cancel:
                        //取消
                        //closePopupWindow();
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }




    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 3, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                Log.w("aadd", "onItemClick: "+position );
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(Test.this).externalPicturePreview(position, "/custom_file", selectList);
                            PictureSelector.create(AddArticle.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(AddArticle.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(AddArticle.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }

    private void saveimgPost( ) {
        openLoading();
        ImgList.clear();
        for (int i=0;i<selectList.size();i++){
            ImgList.add(selectList.get(i).getPath());
        }

        final    String[] arrString = ImgList.toArray(new String[ImgList.size()]) ;
        final     String content=addArticle_content.getText().toString();
        Log.w("aaaa", "saveimgPost: "+arrString.toString() );
        final    Article post = new Article();
        BmobFile.uploadBatch(arrString, new UploadBatchListener() {
            @Override
            public void onSuccess(List<BmobFile> files, List<String> urls) {
                //1、files-上传完成后的BmobFile集合，是为了方便大家对其上传后的数据进行操作，例如你可以将该文件保存到表中
                //2、urls-上传文件的完整url地址
                if(urls.size()==arrString.length){//如果数量相等，则代表文件全部上传完成
                   post.setContent(content);
                    post.setAuthor(BmobUser.getCurrentUser(User.class));//作者
                    post.setPageviewNum(0);//访客记录
                    post.setZanNum(0);
                    post.setPinlunNum(0);
                    post.setLikeNum(0);
                    post.setZhuanfaNum(0);
                    post.setOrderTime(System.currentTimeMillis());
                    if(files.size()>0){
                        post.setImages(files.get(0));
                    }
                    if(files.size()>1){
                        post.setImages2(files.get(1));
                    }
                    if(files.size()>2){
                        post.setImages3(files.get(2));
                    }
                    if(files.size()>3){
                        post.setImages4(files.get(3));
                    }
                    if(files.size()>4){
                        post.setImages5(files.get(4));
                    }
                    if(files.size()>5){
                        post.setImages6(files.get(5));
                    }

                    post.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                addArticle_content.setText("");
                                Log.w("aaaa", "发布帖子成功！" + s);
                                Toast.makeText(AddArticle.this, "发布成功", Toast.LENGTH_LONG).show();
                                closeLoading();
                                Intent intent = new Intent(AddArticle.this, Main.class);
                                intent.putExtra("page", R.id.today_tab);//打开主页
                                startActivity(intent);
                                finish();
                            } else {
                                Log.w("aaaa", "发布帖子失败！" + e.getMessage());
                                closeLoading();
                                Toast.makeText(AddArticle.this, "发布帖子失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                    Log.w("aadd", "上传成功！" );


                }
            }

            @Override
            public void onError(int statuscode, String errormsg) {
                Log.w("aadd","错误码"+statuscode +",错误描述："+errormsg);
            }
            @Override
            public void onProgress(int curIndex, int curPercent, int total,int totalPercent) {
                //1、curIndex--表示当前第几个文件正在上传
                //2、curPercent--表示当前上传文件的进度值（百分比）
                //3、total--表示总的上传文件数
                //4、totalPercent--表示总的上传进度（百分比）
                Log.w("aadd","正在上传："+totalPercent+"%");
            }
        });



    }//带照片的
    private void savePost() {
        openLoading();
        if (BmobUser.isLogin()) {
            Article post = new Article();
            post.setContent(addArticle_content.getText().toString());
                        //添加一对一关联，用户关联帖子
                        post.setAuthor(BmobUser.getCurrentUser(User.class));
                        post.setOrderTime(System.currentTimeMillis());
            post.setPageviewNum(0);//访客记录
            post.setZanNum(0);
            post.setPinlunNum(0);
            post.setLikeNum(0);
            post.setZhuanfaNum(0);
                        post.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if (e == null) {
                                    closeLoading();
                                    addArticle_content.setText("");
                                    Log.w("aaaa", "发布帖子成功！" + s);
                                    Toast.makeText(AddArticle.this,"发布成功" , Toast.LENGTH_LONG).show();
                                    Intent intent = new Intent(AddArticle.this, Main.class);
                                    intent.putExtra("page", R.id.today_tab);//打开主页
                                    startActivity(intent);
                                    finish();
                                } else {
                                    closeLoading();
                                    Log.w("aaaa", "发布帖子失败！" + e.getMessage());
                                    Toast.makeText(AddArticle.this,"发布失败" , Toast.LENGTH_LONG).show();
                                }
                            }
                        });
                    } else {
                        Log.w("aaaa", "请先登录！");

                    }


    }//不带照片的

    public boolean deletefile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }



    //网络加载
    private  void openimgLoading(){

        shapeLoadingDialog = new ShapeLoadingDialog.Builder(AddArticle.this)
                .loadText("图片越大，上传越久哦")
                .build();
        shapeLoadingDialog.show();
    }

    //网络加载
    private  void openLoading(){

        shapeLoadingDialog = new ShapeLoadingDialog.Builder(AddArticle.this)
                .loadText("加载中..")
                .build();
        shapeLoadingDialog.show();
    }

    //关闭网络加载
    private  void closeLoading(){

        shapeLoadingDialog.dismiss();
    }

    public void onBackPressed() {
        //此处写退向后台的处理
        finish();
    }//手机返回键

}
